#include "MyThread.hpp"
#include "LockGuard.hpp"

using namespace ThreadModule;

const int n = 5;
int g_tickets = 10000;


class ThreadData
{
    public:
    ThreadData(int& tickets,string& name,pthread_mutex_t* mutexs)
    :_tickets(tickets)
    ,_name(name)
    ,_total(0)
    ,_mutexs(mutexs)
    {}

    ~ThreadData()
    {}

    int& _tickets;//购买的票数
    string _name;
    int _total;//总计卖出的票数
    pthread_mutex_t* _mutexs; 
};

void func(ThreadData* td)
{
    while(1)
    { 
        LockGuard g(td->_mutexs);//RAII的加解锁
        //pthread_mutex_lock(td->_mutexs);
        if(td->_tickets>0)
        {
            usleep(1000);
            cout<<td->_name<<" buy ticket:"<<td->_tickets<<endl;
            td->_tickets--;
            td->_total++;
            //pthread_mutex_unlock(td->_mutexs);
        }
        else
        {
            //pthread_mutex_unlock(td->_mutexs);
            break;
        }

    }

}


int main()
{
    vector<Thread<ThreadData*>> threads;
    vector<ThreadData*> datas;

    pthread_mutex_t mutex;
    pthread_mutex_init(&mutex,nullptr);
    //mutex mutex;

    //创建一批线程
    for(int i=0;i<n;i++)
    {
        string name = "thread-" + to_string(i+1);
        ThreadData* td = new ThreadData(g_tickets,name,&mutex);
        threads.emplace_back(func, td, name);
        datas.push_back(td);
    }

    //调度一批线程
    for(auto& e : threads)
    {
        e.Strat();
    }

    //等待一批线程
    for(auto& e : threads)
    {
        e.join();
    }

    //统计一下战绩
    for(auto& data : datas)
    {
        cout<<data->_name<<" buy:"<<data->_total<<endl; 
    }

    pthread_mutex_destroy(&mutex);

    return 0;
}
